package com.yzkj.cpjxc.business.controller;

import com.yzkj.cpjxc.business.framework.common.BusinessMap;
import com.yzkj.cpjxc.business.framework.common.CSRFTokenManager;
import com.yzkj.cpjxc.business.framework.common.Constants;
import com.yzkj.cpjxc.business.framework.common.Pager;
import com.yzkj.cpjxc.business.framework.utils.IDUtils;
import com.yzkj.cpjxc.business.framework.utils.WebUtils;
import com.yzkj.cpjxc.business.domain.SysUser;
import com.yzkj.cpjxc.business.system.interceptor.DoLog;
import com.yzkj.cpjxc.business.system.interceptor.Permission;
import com.yzkj.cpjxc.business.domain.Multimedia;
import com.yzkj.cpjxc.business.service.MultimediaService;
import com.yzkj.cpjxc.business.domain.Notification;
import com.yzkj.cpjxc.business.domain.NotificationQueryVo;
import com.yzkj.cpjxc.business.service.NotificationService;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * 通知公告控制器
 */
@Controller
@RequestMapping("/notification")
public class NotificationController extends BaseController {

	@Autowired
	private NotificationService notificationService;

	/**
	 * 多媒体文件Service
	 */
	@Autowired
	private MultimediaService multimediaService;

	/**
	 * 去到通知公告列表页面
	 */
	@RequestMapping("/list")
	@DoLog(cnContent = "去到通知公告列表页面")
	@Permission(name="notification.view")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response, Notification Notification) throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		modelMap.put("Notification", Notification);
		//发布状态MAP
		modelMap.put("GET_INFOSTATE_MAP", Constants.GET_INFOSTATE_MAP);
		//信息类型MAP
		modelMap.put("GET_INFOCONTENTTYPE_MAP", Constants.GET_INFOCONTENTTYPE_MAP);
		//文件类型MAP
		modelMap.put("GET_INFODATATYPE_MAP", Constants.GET_INFODATATYPE_MAP);
		//推送状态MAP
		modelMap.put("GET_ISPUSH_MAP", Constants.GET_ISPUSH_MAP);
		return new ModelAndView("xezz/notification/list").addAllObjects(modelMap);
	}

	/**
	 * 通知公告列表ajax分页
	 */
	@RequestMapping("/ajaxPage")
	@DoLog(cnContent = "通知公告列表ajax分页")
	@Permission(name="notification.view")
	public String ajaxPage(HttpServletRequest request, HttpServletResponse response, NotificationQueryVo vo) throws Exception {
		try {
			Pager<Notification> p = new Pager<Notification>();
			boolean exportExcel = BooleanUtils.toBoolean(request.getParameter(EXPORT_EXCEL));
			if (exportExcel) {
				return null;
			} else {
				String currentPage = request.getParameter(Pager.MY_PAGINATION_CURRENT_PAGE);
				p.setCurrentPage(Integer.parseInt(currentPage == null ? "1" : currentPage));
				Pager<Notification> pager = notificationService.search(p, vo);
				this.genPageJson(response, pager);
				return null;
			}
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	/**
	 * 去到添加通知公告页面
	 */
	@RequestMapping("/toAdd")
	@DoLog(cnContent = "去到添加通知公告页面")
	@Permission(name="notification.add")
	public ModelAndView toAdd(HttpServletRequest request, HttpServletResponse response, Notification notification) throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		//发布状态MAP
		modelMap.put("GET_INFOSTATE_MAP", Constants.GET_INFOSTATE_MAP);
		//信息类型MAP
		modelMap.put("GET_INFOCONTENTTYPE_MAP", Constants.GET_INFOCONTENTTYPE_MAP);
		//文件类型MAP
		modelMap.put("GET_INFODATATYPE_MAP", Constants.GET_INFODATATYPE_MAP);

		return new ModelAndView("xezz/notification/add").addAllObjects(modelMap);
	}

	/**
	 * 添加通知公告
	 */
	@RequestMapping("/add")
	@DoLog(cnContent = "添加通知公告", operationAction = "C")
	@Permission(name="notification.add")
	public String add(HttpServletRequest request, HttpServletResponse response, NotificationQueryVo vo, String[] fileUuid) throws Exception {
		String infoContent = null;
		Multimedia multimedia = null;
		
		//过滤指定非法字符
		//StringHelp.replaceFilteringChars(Notification.class, vo);
		
		try {
			if (vo != null) {
				//自动填充主键UUID
				vo.setUuid(IDUtils.genUUID());
				//设置有效状态 1 有效
				vo.setIsActive(Constants.ACTIVE);
				//设置创建时间
				vo.setCreateTime(new Date());
				//设置推送状态为 2 未推送
				vo.setIsPush("2");
				//如果文件相对路径不为空  则根据路径读取到文件的字节流并将字节流保存到数据库中
				if (StringUtils.isNotBlank(request.getParameter("multimediaUuid"))) {
					multimedia = multimediaService.getById(request.getParameter("multimediaUuid"));
					if(multimedia!=null){
						vo.setFileBlob(multimedia.getFileData());
					}
				}
				infoContent = vo.getInfoContent();
				//替换掉转移字符
				infoContent = infoContent.replace("&lt;","<").replace("&gt;",">").replace("&quot;","\"").replace("&amp;","&");
				vo.setInfoContent(infoContent);
				
			}
			
			SysUser sysUser = (SysUser)request.getSession().getAttribute(Constants.CURRENT_USER);
			if(sysUser!=null){
				vo.setCreator(sysUser.getUsername());
			}
			
			BusinessMap bm = notificationService.create(vo);
			//保存成功，设置检查结果字段是否有关联的文件存在,如果存在则设置Active为启用状态，否则关联文件会被定时清理
			
			//删除临时保存文件
			if(multimedia!=null){
				multimediaService.delete(multimedia.getUuid());
			}
			
			return this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	/**
	 * 查看通知公告
	 */
	@RequestMapping("/view")
	@DoLog(cnContent = "查看通知公告")
	@Permission(name="notification.view")
	public ModelAndView view(HttpServletRequest request, HttpServletResponse response, Notification notification) throws Exception {
		Notification result = notificationService.getById(notification.getUuid());
		return new ModelAndView("xezz/notification/view").addObject("notification", result);
	}

	/**
	 * 删除通知公告
	 */
	@RequestMapping("/delete")
	@DoLog(cnContent = "删除通知公告", operationAction = "D")
	@Permission(name="notification.delete")
	public String delete(HttpServletRequest request, HttpServletResponse response, Notification notification) throws Exception {
		try {
			boolean flag = notificationService.falseDelete(notification.getUuid());
			if (flag) {
				//如果该信息有关联的文件则一并删除
				//multimediaService.deleteByFkUuid(notification.getUuid());
			}
			return this.ajax(response, flag ? Constants.SUCCESS : Constants.ERROR);
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	/**
	 * 通知公告信息发布状态编辑
	 */
	@RequestMapping("/infoStateEdit")
	@DoLog(cnContent = "通知公告信息发布状态编辑", operationAction = "U")
	//@Permission(name="notification.infoStateEdit")
	public String infoStateEdit(HttpServletRequest request, HttpServletResponse response, Notification notification) throws Exception {
		try {
			Notification op = notificationService.getById(notification.getUuid());
			op.setInfoState(notification.getInfoState());
			BusinessMap bm = notificationService.edit(op);
			return this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	/**
	 * 根据ID 提供文件下载
	 */
	@RequestMapping("/download")
	@DoLog(cnContent = "提供文件下载")
	public String downloadApplyFrom(HttpServletRequest request, HttpServletResponse response, Notification notification) throws Exception {
		if (notification != null) {
			Notification op = notificationService.getById(notification.getUuid());
			byte[] fileByte = op.getFileBlob();
			//设置相应头信息
			String infoName = op.getInfoTitleName();
			if (infoName == null) {
				infoName = "文件";
			}
			 String agent=request.getHeader("User-Agent").toLowerCase();
			//如果是IE浏览器
			if(WebUtils.isIe(agent)){
				response.setHeader("Content-Disposition", "attachment;filename=" + new String(infoName.getBytes("GBK"), "iso-8859-1"));
			}else{
				response.setHeader("Content-Disposition", "attachment;filename=" + new String(infoName.getBytes("UTF-8"), "iso-8859-1"));
			}
			OutputStream outputSream = null;
			InputStream in = null;
			try {
				outputSream = response.getOutputStream();
				in = new ByteArrayInputStream(fileByte);
				int len = 0;
				byte[] buf = new byte[1024];
				while ((len = in.read(buf, 0, 1024)) != -1) {
					outputSream.write(buf, 0, len);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (in != null) {
						in.close();
					}
					if (outputSream != null) {
						outputSream.flush();
						outputSream.close();
					}

				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
		return null;
	}

	/**
	 * 去到信息类型列表页面
	 */
	@RequestMapping("/infoType")
	@DoLog(cnContent = "去到信息类型列表页面")
	public ModelAndView infoType(HttpServletRequest request, HttpServletResponse response, Notification notification) throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		//信息类型MAP
		modelMap.put("GET_INFOCONTENTTYPE_MAP", Constants.GET_INFOCONTENTTYPE_MAP);
		return new ModelAndView("xezz/notification/infoType").addAllObjects(modelMap);
	}

	/**
	 * 去到指定下载列表
	 */
	@RequestMapping("/infoTypeList")
	@DoLog(cnContent = "去到指定下载列表")
	public ModelAndView infoTypeList(HttpServletRequest request, HttpServletResponse response, Notification notification) throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		//设置发布状态为：发布
		notification.setInfoState(Constants.INFOSTATE_YES);
		//设置文件类型为：文件下载
		notification.setInfoDataType(Constants.INFODATATYPE_FILE);
		modelMap.put("Notification", notification);
		return new ModelAndView("xezz/notification/infoTypeList").addAllObjects(modelMap);
	}
}
